<?php


namespace app\handler;



use Baseinfo\baseHeader;
use Taskinfo\taskReq;

class RequestHandler
{
    private $serv = '';
    private $fd = '';
    private $receBuf = '';
    private $seq = 0;
    private $handler = '';
    private $body = '';

    /**
     * RequestHandler constructor.
     * @param \Swoole\Server $serv
     * @param int $fd
     * @param string $receBuf
     */
    public function __construct($serv, $fd, $receBuf)
    {
        $this->serv = $serv;
        $this->fd = $fd;
        $this->receBuf = $receBuf;
        $this->unpack();
    }

    public function run()
    {
        $controller = '\\app\\controller\\' . $this->handler .'Controller';


        $class = new $controller;
        $ret = $class->beforeStart();
        if($ret) {
            $class->start();
        }





        $class->start($this->serv, $this->fd, $this->body);
    }

    private function test($controller) {

    }


    private function unpack()
    {
        $headlen = substr($this->receBuf, 1, 4);
        $headlen = unpack('Nlen', $headlen);
        $bodylen = substr($this->receBuf, 5, 4);
        $bodylen = unpack('Nlen', $bodylen);

        $head = substr($this->receBuf, 9, $headlen['len']);
        $header = new baseHeader();
        $header->mergeFromString($head);

        $this->handler = $header->getBytesHandler();
        $this->seq = $header->getInt64Seq();

        $body = substr($this->receBuf, 9 + $headlen['len'], $bodylen['len']);
        $this->body = $body;
    }
}